package com.yuanhua.sim;

import com.yuanhua.auth.server.EnableAuthServer;
import com.yuanhua.core.utils.SpringUtils;
import com.yuanhua.sim.config.AppConfiguration;
import com.yuanhua.sim.netty.serve.NettySocketServer;
import com.yuanhua.sim.thread.RegistryZK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@EnableAuthServer
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class SIMApplication implements CommandLineRunner{

    @Resource
    private AppConfiguration appConfiguration;

    @Resource
    private ApplicationContext context;

    @Value("${server.port}")
    private int httpPort;

    @Resource
    private NettySocketServer nettySocketServer;
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SIMApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        //第一时间启动监听客户端连接请求，把自己注册到zookeeper中；
        //获取本机ip
        String localIp = InetAddress.getLocalHost().getHostAddress();
        Thread zkThread = new Thread(new RegistryZK(localIp, appConfiguration.getSimServerPort(),httpPort));
        zkThread.setName("zk-registry");
        zkThread.start();
        doPrintRunMsg(context);
        nettySocketServer.run();
    }

    private static void doPrintRunMsg(ApplicationContext context) throws UnknownHostException {
        Environment environment = context.getEnvironment();
        String appName = environment.getProperty("spring.application.name");
        String port = environment.getProperty("server.port");
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        //启动完成后在控制台提示项目启动成功，并且输出当前服务对应的swagger接口文档访问地址
        //http://localhost:8080/doc.html
        log.info("应用{}启动成功!swagger地址：http://{}:{}/doc.html",appName,hostAddress,port);
    }
}
